package ru.efimmatytsin.tweeterella.services.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Repository;
import ru.efimmatytsin.tweeterella.entities.User;
import ru.efimmatytsin.tweeterella.services.UserService;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;

/**
 * Created by Efim Matytsin on 14.02.15.
 */

@Repository
public class UserServiceImpl implements UserService {
    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private ConversionService conversionService;

    @Override
    public <T> T getUser(BigInteger id,Class<T> tClass) {
        User result = null;
        if(entityManager.isOpen()){
            result = entityManager.find(User.class,id);
        }
        return conversionService.convert(result, tClass);
    }

    @Override
    public void saveUser(User user) {
        entityManager.persist(user);
    }

    @Override
    public <T> T getUser(String username,Class<T> tClass) {
        Query query = entityManager.createQuery("SELECT e FROM User e where e.username = :username");
        query.setParameter("username",username);
        return conversionService.convert(query.getSingleResult(),tClass);
    }

}
